package other.edan.erp;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.*;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.Account;
import com.rkhd.platform.sdk.data.model.Department;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.CacheException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.edan.erp.apitool.EdanK3Utils;
import other.edan.erp.utils.*;

import java.util.*;

/**
 * @Description 推送客户数据到k3
 * @Author 黎炎松
 * 2024-06-12 09:49
 */
@RestApi(baseUrl = "/xsy/account")
public class AddUpAccountSyncK3 implements Trigger, ApprovalEvent {
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "同步客户数据到k3 ==> ";

    /**
     * trigger 触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + " 触发开始 ");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<Account> accountList = new ArrayList<>();
        for (XObject xObject : dataList) {
            Account account = (Account) xObject;
            accountList.add(account);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        syncAccountToK3(accountList.get(0));
        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    /**
     * 审批流触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public ApprovalEventResponse execute(ApprovalEventRequest request) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + " 触发开始 ");
        logger.info("ObjectApiKey:" + request.getEntityApiKey() + " , DataId:" + request.getDataId());
        logger.info(request.toString());
        ApprovalEventResponse response = new ApprovalEventResponse();
        response.setSuccess(true);
        response.setMsg("success");

        // 执行同步逻辑
        Account account = new Account();
        account.setId(request.getDataId());
        account = HCXObjectService.get(account);
        syncAccountToK3(account);

        return response;
    }


    /**
     * 手动同步客户数据到k3
     * @param id
     * @return
     */
    @RestMapping(value = "/syncK3", method = RequestMethod.POST)
    public String syncK3(@RestQueryParam(name = "id") Long id){
        logger.info(LOGGER_MSG + "执行了手动同步按钮事件：" + id);
        Account account = new Account();
        account.setId(id);
        account = HCXObjectService.get(account);
        return syncAccountToK3(account);
    }

    /**
     * 启用/禁用客户
     * @param id
     * @return
     */
    @RestMapping(value = "/disable", method = RequestMethod.POST)
    public String disableAccount(@RestQueryParam(name = "id") Long id){
        logger.info(LOGGER_MSG + "执行了启用/禁用客户按钮事件：" + id);

        Account account = new Account();
        account.setId(id);
        account = HCXObjectService.get(account);

        // 判断是启用还是禁用 默认生效 crm:1：失效  2：生效  k3: 1:失效 0: 生效
        int upFDeleted = 2;
        int upFStatus = 1072;
        Integer fDeleted = account.getFDeleted__c();
        if (fDeleted == 2) {
            // 失效
            upFDeleted = 1;
            upFStatus = 1074;
        }

        // 更新客户
        Account upAccount = new Account();
        upAccount.setId(id);
        upAccount.setFDeleted__c(upFDeleted); // 生效状态
        upAccount.setFStatus__c(upFStatus); // 客户状态
        HCXObjectService.update(upAccount);

        // 推送k3
        account.setFDeleted__c(upFDeleted); // 生效状态
        account.setFStatus__c(upFStatus); // 客户状态

        String s = syncAccountToK3(account);
        JSONObject obj = JSONObject.parseObject(syncAccountToK3(account));
        if (obj.getIntValue("code") == 0) {
            obj.put("msg", upFDeleted == 1 ? "停用成功" : "启用成功");
            return obj.toString();
        } else {
            return s;
        }
    }

    public static void main(String[] args) throws ApiEntityServiceException, CacheException {
        AddUpAccountSyncK3 addUpAccountSyncK3 = new AddUpAccountSyncK3();

        // 测试推送客户
        Account account = new Account();
        account.setId(3677883437079129L);
        account = HCXObjectService.get(account);
        String s = addUpAccountSyncK3.syncAccountToK3(account);
        System.out.println("s = " + s);

        // 测试禁用客户
        //String s = addUpAccountSyncK3.disableAccount(3380931907967558L);
        //System.out.println("s = " + s);
    }

    /**
     * 同步客户到k3
     * @param account
     */
    public String syncAccountToK3(Account account){
        try {
            logger.info(LOGGER_MSG + "处理开始: " + account);

            // 判断是 渠道 类型的进行同步
            Long entityType = account.getEntityType();
            Integer syncStatus = account.getSyncStatus__c(); // 同步状态
            if (entityType != 3314472397658728L) {
                logger.error(LOGGER_MSG + "当前不是渠道客户,无需推送");
                return TfReturnMsgTools.getFailResult("当前不是渠道客户,无需推送");
            }

            // 判断必填
            List<String> tipsList = new ArrayList<>();
            Map<String, String> fieldMap = new LinkedHashMap<String, String>(){{
                put("crmCode__c", "编号");
                put("fBank__c", "开户银行");
                put("fAccount__c", "银行账号");
                //put("fContact__c", "联系人");
                //put("fPhone__c", "联系电话");
                //put("fEmail__c", "邮件地址");
                put("fTaxNum__c", "税务登记号");
            }};
            for (String key : fieldMap.keySet()) {
                if (account.getAttribute(key) == null) {
                    tipsList.add(fieldMap.get(key));
                }
            }
            if (tipsList.size() > 0) {
                String tips = StringUtils.join(tipsList, ",");
                logger.error(LOGGER_MSG + "开票信息不可为空: " + tips);
                return TfReturnMsgTools.getFailResult(String.format("开票信息不可为空(%s)", tips));
            }

            // 获取【区域代码】通用选项集
            JSONArray regionCodePick = ComUtils.getGlobalPicks("globalPick62__c");
            JSONArray hzhbPick = ComUtils.getGlobalPicks("globalPick187__c"); // 合作伙伴集团属性
            JSONArray hzhbTypePick = ComUtils.getGlobalPicks("globalPick188__c"); // 合作伙伴分类类型

            // 获取所属部门名称
            Department department = new Department();
            department.setId(account.getDimDepart());
            department = HCXObjectService.get(department);

            // 拼接数据
            JSONObject reqData = new JSONObject();
            reqData.put("fOpertype", (syncStatus == null || syncStatus == 1 || syncStatus == 3) ? 1 : 0 ); // 操作： 1:新增
            reqData.put("fNumber", account.getCrmCode__c()); // 编号
            reqData.put("fName", account.getAccountName()); // 名称
            reqData.put("fBank", account.getFBank__c()); // 开户银行
            reqData.put("fContact", account.getFContact__c()); // 联系人
            reqData.put("fEmail", account.getFEmail__c()); // 邮箱地址
            reqData.put("fPhone", account.getFPhone__c()); // 联系电话
            reqData.put("fAddress", account.getAddress()); // 地址
            reqData.put("fAccount", account.getFAccount__c()); // 银行账号
            reqData.put("fTaxNum", account.getFTaxNum__c()); // 税务登记号
            reqData.put("fRegionCode", ComUtils.getOptionApiKey(regionCodePick, account.getFRegionCode__c())); // 区域代码
            reqData.put("fARAccountCode", 113); // 应收账款科目代
            reqData.put("fCrmNumber", account.getCrmCode__c()); // crm编码
            reqData.put("f108", account.getBusinessLicense__c()); // 经营许可证号
            reqData.put("f122", account.getCreatedAt()); // 创建日期
            reqData.put("fStatus", account.getFStatus__c()); // 客户状态
            reqData.put("fDeptName", department.getDepartName()); // 部门名称
            reqData.put("f150", account.getErLeiBeiAn__c()); // 二类备案证号
            reqData.put("f102", "001"); // 国家

            // 是否删除 crm:1：失效  2：生效  k3: 1:失效 0: 生效
            Integer fDeleted = account.getFDeleted__c();
            if (fDeleted == 2) {
                fDeleted = 0; // 避免有其他状态
            }
            reqData.put("fDeleted", fDeleted);

            // 合作伙伴属性
            Integer hzhb = account.getJiTuan__c();
            if (hzhb != null) {
                reqData.put("f139", Integer.valueOf(ComUtils.getOptionApiKey(hzhbPick, hzhb)));
            }

            // 合作伙伴分类类型
            Integer hzhbType = account.getFenLeiType__c();
            if (hzhbType != null) {
                reqData.put("f140", Integer.valueOf(ComUtils.getOptionApiKey(hzhbTypePick, hzhbType)));
            }

            logger.info(LOGGER_MSG + "推送的客户数据:" + reqData);

            // 记录同步状态
            Account upAccount = new Account();
            upAccount.setId(account.getId());
            upAccount.setSyncStatus__c(2); // 同步状态 1：待同步 2：成功 3：首次同步失败 4: 后续同步失败
            upAccount.setFailureReasons__c("");

            // 推送数据到k3
            ResultBody resultBody = EdanK3Utils.sendPost(reqData, EdanK3Utils.ADD_UP_ACCOUNT_URL, "");
            logger.info(LOGGER_MSG + "resultBody:" + resultBody);
            if (!Objects.equals(resultBody.getCode(), "200")) {
                String errMsg = resultBody.getMessage();

                upAccount.setSyncStatus__c((syncStatus == null || syncStatus == 1 || syncStatus == 3) ? 3 : 4); // 同步状态 1：待同步 2：成功 3：首次同步失败 4: 后续同步失败
                upAccount.setFailureReasons__c(errMsg); // 失败原因
                OperateResult update = HCXObjectService.update(upAccount);
                logger.info(LOGGER_MSG + "更新同步状态: " + update.getSuccess());

                logger.error(LOGGER_MSG + "处理失败:" + errMsg);
                return TfReturnMsgTools.getFailResult("推送失败:" + errMsg);
            }

            // 更新同步状态 & 更新用户K3编码
            Object result = resultBody.getResult();
            if (result != null) {
                upAccount.setK3Code__c(result.toString());
            }
            OperateResult update = HCXObjectService.update(upAccount);
            logger.info(LOGGER_MSG + "更新同步状态: " + update.getSuccess());

            logger.info(LOGGER_MSG + "推送成功");
            return TfReturnMsgTools.getSuccessResult("推送成功");
        } catch (Exception e) {
            logger.info(LOGGER_MSG + "处理异常: " + e.getMessage());
            return TfReturnMsgTools.getFailResult("推送异常:" + e.getMessage());
        }
    }


}
